package cn.icatw.leetcode.editor.cn.juc;

import java.util.Arrays;

/**
 * @author 王顺 762188827@qq.com
 * @apiNote 两个线程一个打印奇数一个打印偶数
 * @since 2024/8/6
 */
public class Two {
    static final Object object = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 1; i <= 100; i++) {
                synchronized ((object)) {
                    if (i % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + " " + i);
                        object.notify();
                    } else {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }

            }
        }, "偶数线程");
        Thread t2 = new Thread(() -> {
            for (int i = 1; i <= 100; i++) {
                synchronized ((object)) {
                    if (i % 2 == 1) {
                        System.out.println(Thread.currentThread().getName() + " " + i);
                        object.notify();
                    } else {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }
            }
        }, "奇数线程");
        t1.start();
        t2.start();
        // 主线程等待t1和t2执行完毕
        try {
            for (Thread thread : Arrays.asList(t1, t2)) {
                thread.join();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main end");
    }
}
